package com.longcai.piaojia.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.longcai.piaojia.BaseApplication;
import com.longcai.piaojia.R;
import com.longcai.piaojia.dialog.NoCancleDialog;
import com.longcai.piaojia.util.ScreenShotsUtil;
import com.module.weixin.util.MD5Util;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.util.UtilMD5;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;

/**
 * Created by Administrator on 2016/4/27.
 */
public class WebActivity extends BaseActivity implements View.OnClickListener {

    @BoundView(R.id.title_back_rl) private RelativeLayout title_back_rl;
    @BoundView(R.id.web_wv) private WebView web_wv;
    @BoundView(R.id.web_pb) private ProgressBar web_pb;
    private String title, url;
    private Bundle bundle;
    private String orderJson;
    private boolean isFinish = false;
    private boolean isGoods = false;

    String  getdata;
    @SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        bundle = getIntent().getExtras();

        title = bundle.getString("title", "");
      //  Bundle bundle2=getIntent().getExtras();
    //    getdata=bundle.getString("getdata");
      //  Toast.makeText(context, getdata, Toast.LENGTH_SHORT).show();
        if(title.equals("助力活动")){

            long time = System.currentTimeMillis() / 1000;

            String userId = BaseApplication.BasePreferences.readUserId();

            String  token = MD5Util.MD5Encode(time % Integer.parseInt(userId) + "", "UTF-8") + MD5Util.MD5Encode((time % 13) +"", "UTF-8");

            url = bundle.getString("url", "") + "?user_id=" + userId + "&timestamp=" + time + "&token=" + UtilMD5.MD5Encode(token, "UTF-8");

        }else{

            url = bundle.getString("url", "");

        }

        isGoods = bundle.getBoolean("isGoods", false);

        title_back_rl.setVisibility(View.VISIBLE);

        setTitleName(title);

        // 支持js
        web_wv.getSettings().setJavaScriptEnabled(true);
        web_wv.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

        // 缩放
        web_wv.getSettings().setSupportZoom(true);
        web_wv.getSettings().setBuiltInZoomControls(false);

        web_wv.setWebViewClient(new MyWebViewClient());
        web_wv.setWebChromeClient(wvcc);
        web_wv.addJavascriptInterface(new JavaScriptObject(), "jsObj");

        Log.e("-----", url);

        web_wv.loadUrl(url);

        title_back_rl.setOnClickListener(this);

    }

    public class JavaScriptObject {

        @JavascriptInterface
        public void sub(){

            Log.v("maning", orderJson);

            try {
                JSONObject jsonObject = new JSONObject(orderJson);

                JSONObject body = jsonObject.optJSONObject("body");

                JSONArray jsonArray = body.optJSONArray("ticket");

                String seatArea = "";
                String seatId = "";
                String price = "";

                for(int i=0;i<jsonArray.length();i++){

                    JSONObject object = jsonArray.optJSONObject(i);
                    seatArea = seatArea + "," + object.optString("seat");
                    seatId = seatId + "," + object.optString("seatid");
                    price = price + "," + new BigDecimal(object.optString("price")).setScale(0, BigDecimal.ROUND_HALF_UP).toString();

                }

                Bundle bundle = getIntent().getExtras();

                bundle.putString("money", price.substring(1, price.length()));//数组“,”分割
                bundle.putString("content", seatArea.substring(1, seatArea.length()));
                bundle.putString("seat_id", seatId.substring(1, seatId.length()));

                bundle.putString("goodsCount", body.optString("ordertotalcount"));
                bundle.putString("total_price", body.optString("ordertotalmoney"));
                bundle.putString("ordertotalAmount", body.optString("ordertotalAmount"));
                bundle.putString("orderId", body.optString("orderid"));
                bundle.putString("orderNo", body.optString("orderno"));

                startActivity(new Intent(WebActivity.this, SubmitOrderActivity.class).putExtras(bundle));

                finish();

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(isFinish&&(keyCode == KeyEvent.KEYCODE_BACK)){

            try {
                JSONObject jsonObject = new JSONObject(orderJson);

                JSONObject body = jsonObject.optJSONObject("body");

                JSONArray jsonArray = body.optJSONArray("ticket");

                String seatArea = "";
                String seatId = "";
                String price = "";

                for(int i=0;i<jsonArray.length();i++){

                    JSONObject object = jsonArray.optJSONObject(i);
                    seatArea = seatArea + "," + object.optString("seat");
                    seatId = seatId + "," + object.optString("seatid");
                    price = price + "," + object.optString("price");

                }

                Bundle bundle = getIntent().getExtras();

                bundle.putString("money", price.substring(1, price.length()));//数组“,”分割
                bundle.putString("content", seatArea.substring(1, seatArea.length()));
                bundle.putString("seat_id", seatId.substring(1, seatId.length()));

                bundle.putString("goodsCount", body.optString("ordertotalcount"));
                bundle.putString("total_price", body.optString("ordertotalmoney"));
                bundle.putString("orderId", body.optString("orderid"));
                bundle.putString("orderNo", body.optString("orderno"));

                startActivity(new Intent(WebActivity.this, SubmitOrderActivity.class).putExtras(bundle));

                finish();

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }else if(!isFinish&&(keyCode == KeyEvent.KEYCODE_BACK)){

//            if ((keyCode == KeyEvent.KEYCODE_BACK) && web_wv.canGoBack()) {
//
//                web_wv.goBack();
//
//                return true;
//            }else{
//
//                finish();
//
//            }

//            if ((keyCode == KeyEvent.KEYCODE_BACK) && web_wv.canGoBack()) {
//                web_wv.goBack();
//
//                return true;
//            }else if((keyCode == KeyEvent.KEYCODE_BACK) && !web_wv.canGoBack()){
//
//                finish();
//
//            }

            finish();

        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.title_back_rl:

                if(isFinish){

                    try {
                        JSONObject jsonObject = new JSONObject(orderJson);

                        JSONObject body = jsonObject.optJSONObject("body");

                        JSONArray jsonArray = body.optJSONArray("ticket");

                        String seatArea = "";
                        String seatId = "";
                        String price = "";

                        for(int i=0;i<jsonArray.length();i++){

                            JSONObject object = jsonArray.optJSONObject(i);
                            seatArea = seatArea + "," + object.optString("seat");
                            seatId = seatId + "," + object.optString("seatid");
                            price = price + "," + object.optString("price");

                        }

                        Bundle bundle = getIntent().getExtras();

                        bundle.putString("money", price.substring(1, price.length()));//数组“,”分割
                        bundle.putString("content", seatArea.substring(1, seatArea.length()));
                        bundle.putString("seat_id", seatId.substring(1, seatId.length()));

                        bundle.putString("goodsCount", body.optString("ordertotalcount"));
                        bundle.putString("total_price", body.optString("ordertotalmoney"));
                        bundle.putString("orderId", body.optString("orderid"));
                        bundle.putString("orderNo", body.optString("orderno"));

                        startActivity(new Intent(WebActivity.this, SubmitOrderActivity.class).putExtras(bundle));

                        finish();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }else{

//                    if (web_wv.canGoBack()) {
//
//                        web_wv.goBack();
//
//                    }else{
//
//                        finish();
//
//                    }

                    finish();

                }

                break;

            case R.id.title_right_ll:


                DisplayMetrics metric = new DisplayMetrics();
                this.getWindowManager().getDefaultDisplay().getMetrics(metric);

                // 获取屏幕宽和高
                int widths = metric.widthPixels;
                int heights = metric.heightPixels;

                if (ScreenShotsUtil.myShot(this, widths, heights)) {

                    new NoCancleDialog(context, getString(R.string.please_share_picture_friend_text)).show();

                } else {

                    Toast.makeText(context, "截屏失败", Toast.LENGTH_SHORT).show();

                }

                break;

        }

    }

    private WebChromeClient wvcc = new WebChromeClient() {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);

            Log.v("maning", title);

            if(title.equals("助力二维码")){

                setRightName("截屏", R.color.white, WebActivity.this);

            }

            if(isGoods){

                orderJson = title;

                JSONObject jsonObject = null;

                try {

                    jsonObject = new JSONObject(title);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if(jsonObject!=null){

                    title = "选座完成";
                    isFinish = true;

                }

                setTitleName(title);

            }

        }

    };

//    public static boolean isNumeric1(String str){
//        Pattern pattern = Pattern.compile("[0-9]*");
//        return pattern.matcher(str).matches();
//    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        // 在WebView中而不是默认浏览器中显示页面
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            // 处理电话 短信
            if (url.indexOf("tel:") == 0) {
                String telno = url.substring(4).toString();

                Intent intent = new Intent();
                intent.setAction("android.intent.action.DIAL");
                intent.setData(Uri.parse("tel:" + telno));
                startActivity(intent);

                // Intent intent2 = new Intent(Intent.ACTION_CALL,
                // Uri.parse("tel:" + telno));
                // startActivity(intent2);
            } else if (url.indexOf("sms:") == 0) {
                String smslno = url.substring(4).toString();
                Uri uri = Uri.parse("smsto:" + smslno);
                Intent intent1 = new Intent(Intent.ACTION_SENDTO, uri);
                intent1.putExtra("sms_body", "网站留言：");
                startActivity(intent1);
            } else {
                view.loadUrl(url);
            }
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            // view.loadData(errorHtml, "text/html", "UTF-8");

//            web_wv.setBackgroundColor(0);
//            web_wv.setBackgroundResource(R.drawable.wuwangluo);
//
//            view.loadUrl("file:///android_asset/error.html");
//
//            Toast.makeText(getApplicationContext(), "Sorry 网络不通...",
//                    Toast.LENGTH_SHORT).show();

        }

        @Override
        // 加载完成时要做的工作
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            try {

                web_pb.setVisibility(View.GONE);

            }catch (NullPointerException e){

                e.printStackTrace();

            }

        }

    }

}
